package cn.geminis.crypto.core.util;

import cn.geminis.crypto.core.x509.Crl;
import cn.geminis.crypto.core.x509.X509Certificate;
import cn.geminis.crypto.csp.AbstractCspFactory;
import cn.geminis.crypto.csp.AbstractSigner;
import cn.geminis.crypto.csp.soft.ec.EcCspFactory;
import org.bouncycastle.asn1.x509.ExtendedKeyUsage;
import org.bouncycastle.asn1.x509.Extension;
import org.bouncycastle.asn1.x509.KeyPurposeId;

import java.io.IOException;
import java.math.BigInteger;
import java.time.LocalDateTime;

public class Utils {

    private static final AbstractCspFactory cspFactory = new EcCspFactory("./target/test-out/keys/ec/server", "11111111");

    public static AbstractSigner createSigner() {
        return cspFactory.createSigner();
    }

    public static X509Certificate createSignerCert(AbstractSigner signer) throws IOException {
        var cert = new X509Certificate();
        cert.setSubject("cn=issuer");
        cert.setSerialNumber(BigInteger.ONE);
        cert.setNotBefore(LocalDateTime.now().plusDays(-1));
        cert.setNotAfter(LocalDateTime.now().plusDays(1));
        cert.setPublicKey(signer.getPublicKey());
        var extendedKeyUsage = new ExtendedKeyUsage(KeyPurposeId.id_kp_timeStamping);
        cert.getExtensions().add(new Extension(Extension.extendedKeyUsage, true, extendedKeyUsage.getEncoded()));
        cert.generate(signer);
        return cert;
    }

    public static Crl createCrl(AbstractSigner signer, X509Certificate issuer) {
        var crl = new Crl();
        crl.setNextUpdate(LocalDateTime.now());
        crl.generate(signer, issuer);
        return crl;
    }

}
